﻿using AutoMapper;
using PagedList;
using SIG.DAL.Dapper.Model;
using SIG.DAL.Dapper.Repositories;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Blogs;

using SIG.Resources.Admin;
using SIG.Service;
using SIG.Service.Blogs;
using SIG.ViewModel;
using SIG.ViewModel.Admin.Blogs;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Xml.Linq;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class PostCategoryController : BaseController
    {
        private readonly PostCategoryRepository _categoryRepository;
        private readonly PageMetaRepository _pageMetaService;
        private readonly PostRepository _postService;
        private readonly IMapper _mapper;

        public PostCategoryController(IMapper mapper)
        {
            _categoryRepository = new PostCategoryRepository();
            _postService = new PostRepository();
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;

        }
        // GET: Admin/PostCategory

        #region PostCategory

        public ActionResult Index(int? page, string keyword)
        {
            PostCategoryListVM categoryListVM = GetElements(page, keyword);

            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(categoryListVM);

            //List<PostCategoryVM> vm = GetCategoryList();
            //return View(vm);
        }

        private PostCategoryListVM GetElements(int? page, string keyword)
        {
            var postCategoryListVM = new PostCategoryListVM();

            postCategoryListVM.Keyword = keyword;
            postCategoryListVM.PageIndex = (page ?? 1) ;
            postCategoryListVM.PageSize = SettingsManager.Article.PageSize;
            int totalCount;
            var postCategorylist = _categoryRepository.GetListPagedItems(postCategoryListVM.PageIndex, postCategoryListVM.PageSize, postCategoryListVM.Keyword, out totalCount);
           // var postCategoryVMList = _mapper.Map<List<PostCategory>, List<PostCategoryVM>>(postCategorylist);
            postCategoryListVM.TotalCount = totalCount;
            postCategoryListVM.Categories = new StaticPagedList<PostCategory>(postCategorylist, postCategoryListVM.PageIndex, postCategoryListVM.PageSize, postCategoryListVM.TotalCount); ;
            return postCategoryListVM;
        }

        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/BlogSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        [HttpGet]
        public ActionResult Add()
        {
            var vCategory = new PostCategoryIM();
            vCategory.Active = true;
            vCategory.Importance = 0;

            return PartialView("_Add", vCategory);
        }



        [HttpPost]
        public JsonResult Add(PostCategoryIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var newCategory = _mapper.Map<PostCategoryIM, PostCategory>(vm);
            newCategory.CreatedBy = Site.CurrentUserName;
            newCategory.CreatedDate = DateTime.Now;
            _categoryRepository.Create(newCategory);

            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {
                var pageMeta = new PageMeta()
                {
                    ObjectId = newCategory.Id.ToString(),
                    Keyword = vm.Keywords.Replace('，', ','),
                    Description = vm.SEODescription,
                    ModelType = (short)ModelType.BLOG
                };
                _pageMetaService.Create(pageMeta);
            }

            int count;
            var pageSize = SettingsManager.Article.PageSize;
            var list = _categoryRepository.GetListPagedItems(1, pageSize, string.Empty, out count);
         //   List<PostCategoryVM> categories = _mapper.Map<List<PostCategory>, List<PostCategoryVM>>(list);
            AR.Data = RenderPartialViewToString("_CategoryList", list);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.PostCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            PostCategory category = _categoryRepository.GetById(id);
            if (category == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<PostCategoryIM>(category);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.BLOG, category.Id.ToString());
            if (pageMeta != null)
            {
                vm.Keywords = pageMeta.Keyword;
                vm.SEODescription = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(PostCategoryIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            var newCategory = _categoryRepository.GetById(vm.Id);
            newCategory.Title = vm.Title;
            newCategory.Active = vm.Active;
            newCategory.Importance = vm.Importance;
            newCategory.Description = vm.Description;
            newCategory.SeoName = vm.SeoName;
            newCategory.UpdatedBy = Site.CurrentUserName;
            newCategory.UpdatedDate = DateTime.Now;
           // var newCategory = _mapper.Map<PostCategoryIM, PostCategory>(vm);
            _categoryRepository.Update(newCategory);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.BLOG, vm.Id.ToString());
            pageMeta = pageMeta ?? new PageMeta();


            if (!string.IsNullOrEmpty(vm.Keywords) || !string.IsNullOrEmpty(vm.SEODescription))
            {

                pageMeta.ObjectId = vm.Id.ToString();
                pageMeta.Keyword = vm.Keywords;
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = (short)ModelType.BLOG;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
            }

         //   var category = _mapper.Map<PostCategoryVM>(newCategory);
            AR.Id = newCategory.Id;
            AR.Data = RenderPartialViewToString("_CategoryItem", newCategory);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.PostCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            PostCategory vCategory = _categoryRepository.GetById(id);

            var postCount = _postService.GetCountByParentId(id);
            if (postCount>0)
            {
                AR.Setfailure(string.Format(Messages.HasChildCanNotDelete, EntityNames.PostCategory, EntityNames.Post));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _categoryRepository.Delete(vCategory);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.PostCategory));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vCategory = _categoryRepository.GetById(id);
            if (vCategory == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vCategory.Active = !vCategory.Active;
                _categoryRepository.Update(vCategory);

                var vm = _mapper.Map<PostCategoryVM>(vCategory);

                AR.Data = RenderPartialViewToString("_CategoryItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.PostCategory));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        [AllowAnonymous]
        public JsonResult IsSeoNameUnique(string seoName, int? Id)
        {
            return !IsExist(seoName, Id)
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public bool IsExist(string seoName, int? id)
        {

            if (id > 0)
            {
                return _categoryRepository.IsExistSeoName(seoName, id.Value);
            }
            else
            {
                return _categoryRepository.IsExistSeoName(seoName);
            }
        }



        #endregion
    }
}